#!/usr/bin/env sh

display_help() {
  cat <<'EOH' >&2
Usage: seq [OPTION] LAST
  or:  seq [OPTION] FIRST LAST
  or:  seq [OPTION] FIRST STEP LAST
Display increasing sequence of natural numbers.

Options:
  -f FORMAT   use printf style FORMAT to display an integer
  -s SEP      use SEP to separate numbers (default: \n)
  -h          this message
EOH
}

seq() (

  FORMAT="%d"
  SEP='\n'

  while getopts "hf:s:" opt
  do
    case "$opt" in
      h)
        display_help
        exit
        ;;
      f)
        FORMAT=$OPTARG
        ;;
      s)
        SEP=$OPTARG
        ;;
      *)
        echo "invalid option '$opt'" >&2
        exit 1
        ;;
    esac
  done
  shift $((OPTIND-1))


  case "$#" in
    1)
      start=1
      end=$1
      step=1
      ;;
    2)
      start=$1
      end=$2
      step=1
      ;;
    3)
      start=$1
      end=$3
      step=$2
      ;;
    *)
      display_help
      exit 1
  esac

  i=$start
  while [ "$i" -lt "$end" ]
  do
    printf "$FORMAT$SEP" "$i"
    i=$((i+step))
  done
  [ "$i" -eq "$end" ] && printf "$FORMAT" $i
  echo
  return 0
)

seq "$@"
